package com.ews.onlineexchange.rest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import javax.ws.rs.*;
import javax.ws.rs.core.*;

import com.ews.onlineexchange.util.ActionURIUtils;
import com.ews.onlineexchange.util.PkceGenerator;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import com.ews.onlineexchange.app.CustomMapper;
import com.ews.onlineexchange.app.entity.KeycloakResponse;
import com.ews.onlineexchange.exception.InvalidUsernameAndPasswordException;
import com.ews.onlineexchange.model.ProfessionUser;
import com.ews.onlineexchange.model.ServiceBuyer;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.model.User;
import com.ews.onlineexchange.service.UserService;

import net.sf.json.JSONObject;
import org.keycloak.adapters.spi.HttpFacade;

/**
 * 消息通知接口
 * @author
 *
 */
@Path(value = "/keycloak")
@Transactional
public class KeycloakRest {
	@Inject
	EntityManager entityManager;
	private static final String CLIENT_ID = "onlineExchange";
	private static final String KEYCLOAK_SERVER_URL = "http://localhost:8180/auth/realms/onlineExchangeRealm/protocol/openid-connect/token";
	@Inject
	UserService userService;
	
	@POST
	@Path("/login/{userName}/{password}")
	@Produces("text/html; charset=UTF-8")
	@Context
	public String loginVerify(@PathParam("userName") String userName,@PathParam("password") String password) throws Exception {
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(KEYCLOAK_SERVER_URL);
        post.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
        List<BasicNameValuePair> urlParameters = new ArrayList<BasicNameValuePair>();
        urlParameters.add(new BasicNameValuePair("grant_type", "password"));
        urlParameters.add(new BasicNameValuePair("client_id", CLIENT_ID));
        urlParameters.add(new BasicNameValuePair("username", userName));
        urlParameters.add(new BasicNameValuePair("password", password));
//      urlParameters.add(new BasicNameValuePair("redirect_uri", "http%3A%2F%2Flocalhost%3A80%2Fbusiness%2Fsupplier%2FUnapplyTradeList.xhtml"));
        CustomMapper mapper = new CustomMapper();
        KeycloakResponse keycloakResponse = new KeycloakResponse();
		 post.setEntity(new UrlEncodedFormEntity(urlParameters,"utf-8"));
	     HttpResponse response = client.execute(post);
	     int statusCode = response.getStatusLine().getStatusCode();
		 System.out.println("Response Code : " + statusCode);
	     BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
	     StringBuffer result = new StringBuffer();
	     String line1 = "";
	     while ((line1 = rd.readLine()) != null) {
	         result.append(line1);
	     }
	     System.out.println(result);
	     keycloakResponse.setStatusCode(statusCode);
	     keycloakResponse.setResult(result.toString());
	     if(200 == statusCode) {
	    	 User loginedUser = userService.findByUsername(userName);
	    	 if(null != loginedUser) {
	    		 keycloakResponse.setLoginedUser((loginedUser));
	    		 if(loginedUser instanceof ServiceSupplier) {
	    			 keycloakResponse.setUserType("ServiceSupplier");
	    			 User user = new User();
	    			 user.setCnname(loginedUser.getCnname());
	    			 user.setId(loginedUser.getId());
	    			 keycloakResponse.setLoginedUser((user));
	    		 }
	    		 if(loginedUser instanceof ServiceBuyer) keycloakResponse.setUserType("ServiceBuyer");
	    		 if(loginedUser instanceof ProfessionUser) keycloakResponse.setUserType("ProfessionUser");
	    	 }
	     }
		return mapper.writeValueAsString(keycloakResponse);
	}
	public static void main(String[] args) {


	}
	
}
